package DesignModel;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by tiang on 2018/7/19.
 * 动态代理模式
 */
public class DynamicProxy {
    interface Action{
        void act();
    }

    private static class EatAction implements Action{

        @Override
        public void act() {
            System.out.println("I am eating.");
        }
    }

    private static class ProxyGenerator implements InvocationHandler{

        private Object aim;

        /**
         * 生成一个代理对象，这个对象的执行者为this，代理对象调用指定方法的时候，会调用this.invoke方法
         * @param obj
         * @return
         */
        public Object bind(Object obj){
            aim = obj;
            Class[] interfaces = obj.getClass().getInterfaces();
            return Proxy.newProxyInstance(this.getClass().getClassLoader(), interfaces, this);
        }
        /**
         * 返回调用结果
         * @param proxy 需要代理的目标类
         * @param method 指定的方法
         * @param args 方法的参数
         * @return
         * @throws Throwable
         */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println(proxy.getClass());
            Object result = null;
            if(aim instanceof EatAction){
                System.out.println("before eating");
                result = method.invoke(aim, args);
                System.out.println("after eating");
            }
            return result;
        }
    }

    public static void main(String[] args) throws Throwable {
        ProxyGenerator generator = new ProxyGenerator();
        Action action = (Action) generator.bind(new EatAction());
        action.act();
        System.out.println(action.getClass());
//        System.out.println(action.toString());
    }
}
